<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        .container {
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .chat-window {
            background-color: #fff;
            border-radius: 5px;
            overflow-y: scroll;
            height: 400px;
            padding: 10px;
            margin-bottom: 10px;
        }

        .message {
            padding: 5px;
            border-bottom: 1px solid #ddd;
        }

        .message .name {
            font-weight: bold;
        }

        .message .text {
            margin-left: 10px;
        }

        .input-area {
            display: flex;
        }

        .input-area input {
            flex: 1;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .input-area button {
            margin-left: 10px;
            padding: 5px 10px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chat-window" id="chatWindow"></div>
        <div class="input-area">
            <input type="text" id="messageInput" placeholder="输入消息...">
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>
    <script>
        // 发送消息的函数
        async function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const data = { message: messageInput.value };
            
            try {
                const response = await fetch('http://localhost:5000/api/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    const result = await response.json();
                    messageInput.value = "";
                    alert('消息已发送！');
                    // updateChatWindow(result.greeting); 可以取消注释以在发送消息后更新聊天窗口
                } else {
                    console.error('Error sending message:', response.status);
                }
            } catch (error) {
                console.error('Error sending message:', error);
            }
        }

        // 更新聊天窗口的函数
        function updateChatWindow(message) {
            const chatWindow = document.getElementById('chatWindow');
            const messageElement = document.createElement('div');
            messageElement.classList.add('message');
            messageElement.innerHTML = `
                <div class="name">System</div>
                <div class="text">${message}</div>
            `;
            chatWindow.appendChild(messageElement);
            chatWindow.scrollTop = chatWindow.scrollHeight;
        }

        // 获取聊天记录并渲染到聊天窗口的函数
        async function fetchAndDisplayChatLog() {
            try {
                const response = await fetch('http://localhost:5000/api/chat_log');
                if (response.ok) {
                    const chatLog = await response.json();
                    // 清空聊天窗口
                    document.getElementById('chatWindow').innerHTML = '';
                    chatLog.forEach(line => {
                        const parts = line.split(', Message: ');
                        const ip = parts[0].split('IP: ')[1];
                        const text = parts[1];
                        updateChatWindow(`${ip}: ${text}`);
                    });
                } else {
                    console.error('Error fetching chat log:', response.status);
                }
            } catch (error) {
                console.error('Error fetching chat log:', error);
            }
        }

        // 页面加载完成后获取聊天记录
        document.addEventListener('DOMContentLoaded', function() {
            setInterval(fetchAndDisplayChatLog, 2000);
        });
    </script>
</body>
</html>